package gestordeentidades.gateways;

import entidades.Ponto;
import gestordeentidades.identitymap.interfaces.IEntityMap;
import gestordeentidades.persistance.database.Converter;
import gestordeentidades.persistance.interfaces.IDataBaseAdapter;
import gestordeentidades.persistance.interfaces.IDataBaseRow;
import gestordeentidades.persistance.interfaces.IDataBaseStatement;
import gestordeentidades.persistance.interfaces.IGateway;
import gestordeentidades.persistance.interfaces.ILinha;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import entidades.Rectangulo;
import entidades.Telha;

/**
 * Trabalho DAS - 2014/2015
 * @author a21210380, a21190325, a21210392
 */
public class RectanguloGateway implements IGateway<Rectangulo> {
    private static final Logger logger = Logger.getLogger(RectanguloGateway.class.getName());

    public static final String SQL_CREATE = "CREATE TABLE IF NOT EXISTS rectangulo ("
            + "id " + Converter.convertToSqlText(int.class) + " NOT NULL,"
            + "id_ponto " + Converter.convertToSqlText(int.class) + " NOT NULL,"
            + "largura " + Converter.convertToSqlText(float.class) + " NOT NULL,"
            + "altura " + Converter.convertToSqlText(float.class) + " NOT NULL);";
    public static final String SQL_DROP = "DROP TABLE rectangulo;";
    public static final String SQL_INSERT = "INSERT INTO rectangulo VALUES (?,?,?,?);";
    public static final String SQL_UPDATE = "UPDATE rectangulo SET id_ponto=?,largura=?,altura=? WHERE id=?;";
    public static final String SQL_DELETE = "DELETE FROM rectangulo WHERE id=?;";
    public static final String SQL_FIND_BY_ID = "SELECT * FROM rectangulo WHERE id=?;";
    public static final String SQL_FIND_ALL = "SELECT * FROM rectangulo;";
    
    @Override
    public void initTable(IDataBaseAdapter dataBase) {
        dataBase.executarSql(SQL_CREATE);
    }

    @Override
    public void dropTable(IDataBaseAdapter dataBase) {
        dataBase.executarSql(SQL_DROP);
    }

    @Override
    public boolean inserirNovaEntidade(IDataBaseAdapter dataBase, Rectangulo object) {
        IDataBaseStatement statement = dataBase.getDataBaseStatement(SQL_INSERT);
        statement.adicionarParametroSql(1, object.getId(), Converter.convertToSqlText(int.class));
        statement.adicionarParametroSql(2, object.getOrigem().getId(), Converter.convertToSqlText(int.class));
        statement.adicionarParametroSql(3, object.getLargura(), Converter.convertToSqlText(float.class));
        statement.adicionarParametroSql(4, object.getAltura(), Converter.convertToSqlText(float.class));
        return (dataBase.inserir(statement) == 1);
    }

    @Override
    public boolean atualizarEntidade(IDataBaseAdapter dataBase, Rectangulo object) {
        IDataBaseStatement statement = dataBase.getDataBaseStatement(SQL_UPDATE);
        statement.adicionarParametroSql(1, object.getOrigem().getId(), Converter.convertToSqlText(int.class));
        statement.adicionarParametroSql(2, object.getLargura(), Converter.convertToSqlText(float.class));
        statement.adicionarParametroSql(3, object.getAltura(), Converter.convertToSqlText(float.class));
        statement.adicionarParametroSql(4, object.getId(), Converter.convertToSqlText(int.class));
        return (dataBase.atualizar(statement) == 1);
    }

    @Override
    public boolean apagarEntidade(IDataBaseAdapter dataBase, Rectangulo object) {
        IDataBaseStatement statement = dataBase.getDataBaseStatement(SQL_DELETE);
        statement.adicionarParametroSql(1, object.getId(), Converter.convertToSqlText(int.class));
        return (dataBase.atualizar(statement) == 1);
    }

    @Override
    public Rectangulo procurarEntidadePeloID(IDataBaseAdapter dataBase, IEntityMap entityMap, int id) {
        IDataBaseStatement statement = dataBase.getDataBaseStatement(SQL_FIND_BY_ID);
        statement.adicionarParametroSql(1, id, Converter.convertToSqlText(int.class));
        ProcurarPorID p = new ProcurarPorID(entityMap);
        dataBase.ler(statement, p);
        return p.getRectangulo();
    }

    @Override
    public Map<Integer, Rectangulo> procurarPorTodasAsEntidadesComoMapa(IDataBaseAdapter dataBase, IEntityMap entityMap) {
        IDataBaseStatement statement = dataBase.getDataBaseStatement(SQL_FIND_ALL);
        ProcurarComoMapa p = new ProcurarComoMapa(entityMap);
        dataBase.ler(statement, p);
        return p.getRectangulos();
    }
    
    private class ProcurarPorID implements IDataBaseRow {
        private final IEntityMap entityMap;
        private Rectangulo rectangulo = null;

        ProcurarPorID(IEntityMap entityMap) {
            this.entityMap = entityMap;
        }
        
        public Rectangulo getRectangulo() {
            return rectangulo;
        }

        @Override
        public void onLinhaLida(ILinha linha) {
            int id = linha.getInt("id");
            int id_ponto = linha.getInt("id_ponto");
            float largura = linha.getFloat("largura");
            float altura = linha.getFloat("altura");

            Rectangulo r = new Rectangulo(
                    entityMap.procurarEntidadePeloID(Ponto.class, id_ponto), 
                    altura, 
                    largura,
                    Telha.MIN_SIZE);
            
            Field idField;
            try {
                idField = r.getClass().getSuperclass().getDeclaredField("id");
                idField.setAccessible(true);

                idField.setInt(r, id);
                rectangulo = r;
            } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
                logger.logp(Level.SEVERE, RectanguloGateway.class.getName(), "ProcurarComoMapa-onLinhaLida()", "Reflection API!", ex);
            }
        }
    }
    
    private class ProcurarComoMapa implements IDataBaseRow {
        private final IEntityMap entityMap;
        private final Map<Integer, Rectangulo> mapa = new HashMap<>();

        ProcurarComoMapa(IEntityMap entityMap) {
            this.entityMap = entityMap;
        }
        
        public Map<Integer, Rectangulo> getRectangulos() {
            return mapa;
        }

        @Override
        public void onLinhaLida(ILinha linha) {
            int id = linha.getInt("id");
            int id_ponto = linha.getInt("id_ponto");
            float largura = linha.getFloat("largura");
            float altura = linha.getFloat("altura");

            Rectangulo r = new Rectangulo(
                    entityMap.procurarEntidadePeloID(Ponto.class, id_ponto), 
                    altura, 
                    largura,
                    Telha.MIN_SIZE);
            
            Field idField;
            try {
                idField = r.getClass().getSuperclass().getDeclaredField("id");
                idField.setAccessible(true);

                idField.setInt(r, id);
                mapa.put(id, r);
            } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
                logger.logp(Level.SEVERE, RectanguloGateway.class.getName(), "ProcurarComoMapa-onLinhaLida()", "Reflection API!", ex);
            }
        }
    }

}
